/**
 * ICustomAlertTaskService.java
 * Created at 2017-11-1
 * Created by zhanghailin
 * Copyright (C) 2017 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.rms.timetask.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.broadtext.common.exp.DaoException;
import com.broadtext.common.exp.ServiceException;
import com.broadtext.common.repository.EntityDao;
import com.broadtext.common.service.impl.EntityServiceImpl;
import com.broadtext.common.utils.DateUtils;
import com.broadtext.common.utils.StringUtils;
import com.broadtext.rms.monitor.model.TtPackCurrent;
import com.broadtext.rms.timetask.model.TtPackCustomAlertTask;
import com.broadtext.rms.timetask.service.ICustomAlertTaskService;

/**
 * <p>ClassName: ICustomAlertTaskService</p>
 * <p>Description: TODO</p>
 * <p>Author: zhanghailin</p>
 * <p>Date: 2017-11-1</p>
 */
@Service("customAlertTaskService")
public class CustomAlertTaskService extends EntityServiceImpl<TtPackCustomAlertTask> implements ICustomAlertTaskService{
    
    /**
     * 日志
     */
    private static Logger logger = LoggerFactory.getLogger(CustomAlertTaskService.class);
    /**
     * 
     * <p>Description: 基类dao</p>
     * @param entityDao 基类实体dao
     */
    @Autowired
    @Qualifier("CustomAlertTaskDao")
    public void setEntityDao(EntityDao<TtPackCustomAlertTask> entityDao) {
        super.entityDao = entityDao;
    }
    
    @SuppressWarnings("unchecked")
    public List<TtPackCurrent> findTtPackDataList(Map<String,String> queryMap) throws ServiceException{
        List<TtPackCurrent> list = new ArrayList<TtPackCurrent>();
        try {
            list = this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.getTtPackData", queryMap);
        } catch (DaoException e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
        return list;
        
    }

    /** (non-Javadoc)
     * <p>Title: batchInsertData</p>
     * <p>Description: </p>
     * @param taskList
     * @throws ServiceException
     * @see com.broadtext.timetask.service.ICustomAlertTaskService#batchInsertData(java.util.List)
     */
    @Override
    public void batchInsertData(List<TtPackCustomAlertTask> taskList) throws ServiceException {
        if(taskList!=null&&taskList.size()>0){
            try {
                for (TtPackCustomAlertTask ttPackCustomAlertTask : taskList) {
                    this.entityDao.insertRecord("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.insertRecord", ttPackCustomAlertTask);
                }
            }catch (DaoException e) {
                e.printStackTrace();
            }
        } 
        
    }
    
            
    

    /** (non-Javadoc)
     * <p>Title: getQueryTime</p>
     * <p>Description: </p>
     * @return
     * @throws ServiceException
     * @see com.broadtext.rms.timetask.service.ICustomAlertTaskService#getQueryTime()
     */
    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> getQueryTime() throws ServiceException {
        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            list = this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.getQueryTime", null);
            if(list!=null&&list.size()>0){
                map = list.get(0);
            }
        } catch (DaoException e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
        return map;
    }

    /** (non-Javadoc)
     * <p>Title: updateTaskTime</p>
     * <p>Description: </p>
     * @param queryEndTime
     * @throws ServiceException
     * @see com.broadtext.rms.timetask.service.ICustomAlertTaskService#updateTaskTime(java.util.Date)
     */
    @Override
    public void updateTaskTime(String queryEndTime) throws ServiceException {
        try {
            this.entityDao.updateRecord("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.updateTaskTime", queryEndTime);
        } catch (DaoException e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
    }

    /** (non-Javadoc)
     * <p>Title: createBatteryChargeData</p>
     * <p>Description: </p>
     * @param gatherTimeStart
     * @param gatherTimeEnd
     * @throws ServiceException
     * @see com.broadtext.rms.timetask.service.ICustomAlertTaskService#createBatteryChargeData(java.lang.String, java.lang.String)
     */
    @Override
    public void createBatteryChargeData(Map<String, Object> map) throws ServiceException {
        try {
            this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.createBatteryChargeData", map);
        } catch (DaoException e) {
            e.printStackTrace();
        }
    }

    /** (non-Javadoc)
     * <p>Title: carryOverPackVolData</p>
     * <p>Description: 结转电池单体电压数据，插入tt_cellvoltage_his_表中
     * 调存储过程pro_jz_vol_data(IN `suffix` varchar(32), IN `gathertime_start` varchar(32),IN `gathertime_end` varchar(32))
     * suffix子表后缀 gathertime_start gathertime_end 结转数据时间条件
     * </p>
     * @param params
     * @see com.broadtext.rms.timetask.service.ICustomAlertTaskService#carryOverPackVolData()
     */
    @SuppressWarnings("unchecked")
    @Override
    public void carryOverPackVolData() {
        try {
            //查询结转数据时间条件
            Map<String, Object> map = new HashMap<String, Object>();
            List<Map<String, Object>> list = this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.getCarryOverVolTime", null);
            if(list!=null&&list.size()>0&&list.get(0)!=null){
                map = list.get(0);
                Date date = new Date();
                //SimpleDateFormat f =  new SimpleDateFormat("yyyyMM");
                //String suffix = f.format(date);
                //map.put("suffix", suffix);
                //判断结转开始时间和结束时间是否在同一个月，不同月份数据插入的子表不同
                SimpleDateFormat f1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String gatherTimeEnd = f1.format(date);
                map.put("gatherTimeEnd", gatherTimeEnd);
                String gatherTimeStart = map.get("gatherTimeStart").toString();
                Date startDate = f1.parse(gatherTimeStart);
                String suffix = getCarryOverParams(startDate);
                map.put("suffix", suffix);
                if(!gatherTimeEnd.substring(8,10).equals(gatherTimeStart.substring(8,10))){
                    gatherTimeEnd = DateUtils.getDayStartStr(date);
                    map.put("gatherTimeEnd", gatherTimeEnd);
                }
                //结转数据
                this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.carryOverPackVolData", map);
                //更新结转时间条件
                this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.updateCarryOverVolDataTime", gatherTimeEnd);
            }else {
                logger.info("查询电池单体电压结转时间条件失败！");
            }
        } catch (DaoException e) {
            e.printStackTrace();
            logger.info("结转单体电压数据失败！");
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    
    /** (non-Javadoc)
     * <p>Title: carryOverPackVolData</p>
     * <p>Description: 结转电池监测点温度数据，插入tt_temp_his_表中
     * 调存储过程pro_jz_temp_data(IN `suffix` varchar(32), IN `gathertime_start` varchar(32),IN `gathertime_end` varchar(32))
     * suffix子表后缀 gathertime_start gathertime_end 结转数据时间条件
     * </p>
     * @param params
     * @see com.broadtext.rms.timetask.service.ICustomAlertTaskService#carryOverPackVolData()
     */
    @SuppressWarnings("unchecked")
    @Override
    public void carryOverPackTempData() {
        try {
            //查询结转数据时间条件
            Map<String, Object> map = new HashMap<String, Object>();
            List<Map<String, Object>> list = this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.getCarryOverTempTime", null);
            if(list!=null&&list.size()>0&&list.get(0)!=null){
                map = list.get(0);
                Date date = new Date();
                //SimpleDateFormat f =  new SimpleDateFormat("yyyyMM");
                //String suffix = f.format(date);
                //map.put("suffix", suffix);
                //判断结转开始时间和结束时间是否在同一个月，不同月份数据插入的子表不同
                SimpleDateFormat f1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String gatherTimeEnd = f1.format(date);
                map.put("gatherTimeEnd", gatherTimeEnd);
                String gatherTimeStart = map.get("gatherTimeStart").toString();
                Date startDate = f1.parse(gatherTimeStart);
                String suffix = getCarryOverParams(startDate);
                map.put("suffix", suffix);
                if(!gatherTimeEnd.substring(8,10).equals(gatherTimeStart.substring(8,10))){
                    gatherTimeEnd = DateUtils.getDayStartStr(date);
                    map.put("gatherTimeEnd", gatherTimeEnd);
                }
                //结转数据
                this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.carryOverPackTempData", map);
                //更新结转时间条件
                this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.updateCarryOverTempDataTime", gatherTimeEnd);
            }else {
                logger.info("查询电池监测点温度结转时间条件失败！");
            }
        } catch (DaoException e) {
            e.printStackTrace();
            logger.info("结转监测点温度数据失败！");
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    /** (non-Javadoc)
     * <p>Title: carryOverPackBasicData</p>
     * <p>Description: 结转电池监测点温度数据，插入tt_pack_his_表中
     * 调存储过程pro_jz_pack_data(IN `suffix` varchar(32), IN `gathertime_start` varchar(32),IN `gathertime_end` varchar(32))
     * suffix子表后缀 gathertime_start gathertime_end 结转数据时间条件
     * </p>
     * @param params
     * @see com.broadtext.rms.timetask.service.ICustomAlertTaskService#carryOverPackBasicData()
     */
    @SuppressWarnings("unchecked")
    @Override
    public void carryOverPackBasicData() {
        try {
            //查询结转数据时间条件
            Map<String, Object> map = new HashMap<String, Object>();
            List<Map<String, Object>> list = this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.getCarryOverBasicTime", null);
            if(list!=null&&list.size()>0&&list.get(0)!=null){
                map = list.get(0);
                Date date = new Date();
                SimpleDateFormat f =  new SimpleDateFormat("yyyyMM");
                String suffix = f.format(date);
                map.put("suffix", suffix);
                //判断结转开始时间和结束时间是否在同一个月，不同月份数据插入的子表不同
                SimpleDateFormat f1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String gatherTimeEnd = f1.format(date);
                map.put("gatherTimeEnd", gatherTimeEnd);
                String gatherTimeStart = map.get("gatherTimeStart").toString();
                if(!gatherTimeEnd.substring(5,7).equals(gatherTimeStart.substring(5,7))){
                    gatherTimeEnd = DateUtils.getDayStartStr(date);
                    map.put("gatherTimeEnd", gatherTimeEnd);
                }
                //结转数据
                this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.carryOverPackBasicData", map);
                //更新结转时间条件
                this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.updateCarryOverBasicDataTime", gatherTimeEnd);
            }else {
                logger.info("查询电池结转时间条件失败！");
            }
        } catch (DaoException e) {
            e.printStackTrace();
            logger.info("结转电池数据失败！");
        } 
    }
    
    private static String getCarryOverParams(Date date){
        SimpleDateFormat formatMonth = new SimpleDateFormat("yyyyMM");
        SimpleDateFormat formatDay = new SimpleDateFormat("dd");
        //Date date = new Date();
        String prefix = formatMonth.format(date);
        String suffix = formatDay.format(date);
        String a = suffix.substring(0,1);
        String b = suffix.substring(0,1);
        int c = 0;
        if(Integer.valueOf(a)==0){
            c = Integer.valueOf(b);
        }else {
            c = Integer.valueOf(suffix);
        }
        if(c>=0&&c<5){
            suffix = "01";
        }else if(c>=5&&c<10){
            suffix = "05";
        }else if(c>=10&&c<15){
            suffix = "10";
        }else if(c>=15&&c<20){
            suffix = "15";
        }else if(c>=20&&c<25){
            suffix = "20";
        }else if(c>=25){
            suffix = "25";
        }
        return prefix+suffix;
    }
    
    public static void main(String[] args) {
        String str = DateUtils.getPastDate(7);
        System.out.println(str);
        
    }

    /** (non-Javadoc)
     * <p>Title: deleteVolLastDayData</p>
     * <p>Description: </p>
     * @see com.broadtext.rms.timetask.service.ICustomAlertTaskService#deleteVolLastDayData()
     */
    @SuppressWarnings("unchecked")
    @Override
    public void deleteVolLastDayData() {
        //查询结转数据时间条件
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            //查询上次结转任务结转开始时间
            List<Map<String, Object>> list = this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.getCarryOverVolTime", null);
            if(list!=null&&list.size()>0&&list.get(0)!=null){
                map = list.get(0);
                SimpleDateFormat f1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String gatherTimeStart = map.get("gatherTimeStart").toString();
                Date startDate = f1.parse(gatherTimeStart);
                //查询当天数据插入的表
                String tableName = "tt_cellvoltage_his_"+getCarryOverParams(startDate);
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("tableName", tableName);
                //查询当前表数据的最大采集时间
                List<Map<String, Object>> maxGatherTimeList = this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.findMaxGatherTime", params);
                if(maxGatherTimeList!=null&&maxGatherTimeList.size()>0&&maxGatherTimeList.get(0)!=null){
                    Map<String, Object> gatherTimeMap = maxGatherTimeList.get(0);
                    String maxGatherTime = gatherTimeMap.get("gatherTime").toString();
                    if(StringUtils.isNotBlank(maxGatherTime)&&!"null".equals(maxGatherTime)){
                        Date maxGatherDate = f1.parse(maxGatherTime);
                        Date yesterDayEndDate = DateUtils.getYesterdayEnd();
                        //比较当前表中的最大采集时间是否大于昨天结束时间，若大于，删除昨天的数据（目的是减轻查询压力）
                        if(maxGatherDate.getTime()>=yesterDayEndDate.getTime()){
                            String gatherTime = DateUtils.getYesterdayEndStr();
                            this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.deleteVolData", gatherTime);
                        }
                    }
                }
            }
        } catch (DaoException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /** (non-Javadoc)
     * <p>Title: deleteTempLastDayData</p>
     * <p>Description: </p>
     * @see com.broadtext.rms.timetask.service.ICustomAlertTaskService#deleteTempLastDayData()
     */
    @SuppressWarnings("unchecked")
    @Override
    public void deleteTempLastDayData() {
      //查询结转数据时间条件
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            //查询上次结转任务结转开始时间
            List<Map<String, Object>> list = this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.getCarryOverTempTime", null);
            if(list!=null&&list.size()>0&&list.get(0)!=null){
                map = list.get(0);
                SimpleDateFormat f1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String gatherTimeStart = map.get("gatherTimeStart").toString();
                Date startDate = f1.parse(gatherTimeStart);
                //查询当天数据插入的表
                String tableName = "tt_point_temp_his_"+getCarryOverParams(startDate);
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("tableName", tableName);
                //查询当前表数据的最大采集时间
                List<Map<String, Object>> maxGatherTimeList = this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.findMaxGatherTime", params);
                if(maxGatherTimeList!=null&&maxGatherTimeList.size()>0&&maxGatherTimeList.get(0)!=null){
                    Map<String, Object> gatherTimeMap = maxGatherTimeList.get(0);
                    String maxGatherTime = gatherTimeMap.get("gatherTime").toString();
                    if(StringUtils.isNotBlank(maxGatherTime)&&!"null".equals(maxGatherTime)){
                        Date maxGatherDate = f1.parse(maxGatherTime);
                        Date yesterDayEndDate = DateUtils.getYesterdayEnd();
                        //比较当前表中的最大采集时间是否大于昨天结束时间，若大于，删除昨天的数据（目的是减轻查询压力）
                        if(maxGatherDate.getTime()>=yesterDayEndDate.getTime()){
                            String gatherTime = DateUtils.getYesterdayEndStr();
                            this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.deleteTempData", gatherTime);
                        }
                    }
                }
            }
        } catch (DaoException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        
    }

    /** (non-Javadoc)
     * <p>Title: deleteBasicLastDayData</p>
     * <p>Description: </p>
     * @see com.broadtext.rms.timetask.service.ICustomAlertTaskService#deleteBasicLastDayData()
     */
    @Override
    public void deleteBasicLastDayData() {
        
    }

    /* (non-Javadoc)
     * <p>Title: createVolTable</p>
     * <p>Description: </p>
     * @see com.broadtext.rms.timetask.service.ICustomAlertTaskService#createVolTable()
     */
    @Override
    public void createVolTable() {
        String[] tableSuffixs = new String[]{"01","05","10","15","20","25"};
        Date nextMonth = DateUtils.getNextMonthBegin();
        SimpleDateFormat f = new SimpleDateFormat("yyyyMM");
        String prefix = f.format(nextMonth);
        Map<String, Object> params = new HashMap<String, Object>();
        try {
            for (int i = 0; i < tableSuffixs.length; i++) {
                String suffix = prefix+tableSuffixs[i];
                params.put("suffix", suffix);
                    this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.createVolTable", params);
            }
        } catch (DaoException e) {
            e.printStackTrace();
        }
    }

    /* (non-Javadoc)
     * <p>Title: createTempTable</p>
     * <p>Description: </p>
     * @see com.broadtext.rms.timetask.service.ICustomAlertTaskService#createTempTable()
     */
    @Override
    public void createTempTable() {
        String[] tableSuffixs = new String[]{"01","05","10","15","20","25"};
        Date nextMonth = DateUtils.getNextMonthBegin();
        SimpleDateFormat f = new SimpleDateFormat("yyyyMM");
        String prefix = f.format(nextMonth);
        Map<String, Object> params = new HashMap<String, Object>();
        try {
            for (int i = 0; i < tableSuffixs.length; i++) {
                String suffix = prefix+tableSuffixs[i];
                params.put("suffix", suffix);
                    this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.createTempTable", params);
            }
        } catch (DaoException e) {
            e.printStackTrace();
        }
        
    }

    /* (non-Javadoc)
     * <p>Title: createPackBaiscTable</p>
     * <p>Description: </p>
     * @see com.broadtext.rms.timetask.service.ICustomAlertTaskService#createPackBaiscTable()
     */
    @Override
    public void createPackBaiscTable() {
        SimpleDateFormat f = new SimpleDateFormat("yyyyMM");
        Date nextMonth = DateUtils.getNextMonthBegin();
        String suffix = f.format(nextMonth);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("suffix", suffix);
        try {
             this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.createPackBaiscTable", params);
        } catch (DaoException e) {
            e.printStackTrace();
        }
        
    }

	@Override
	public void carryOverScreenData() throws DaoException {
		this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.createScreenData", null);
	}


    @Override
    public void deleteTempData() throws DaoException {
        String gatherTime = DateUtils.getPastDate(7);
        logger.info("gathertime:{}",gatherTime);
        this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.deleteTempData", gatherTime);
    }

    @Override
    public void deleteVolData() throws DaoException {
        String gatherTime = DateUtils.getPastDate(7);
        logger.info("gathertime:{}",gatherTime);
        this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.deleteVolData", gatherTime);
    }

    @Override
    public void deletePackBasicData() throws DaoException {
        String gatherTime = DateUtils.getPastDate(7);
        logger.info("gathertime:{}",gatherTime);
        this.entityDao.findByProperty("com.broadtext.rms.timetask.model.TtPackCustomAlertTask.deletePackBasicData", gatherTime);
    }
}
